#coding=utf-8
# -*- coding: utf-8 -*-

# 输入git仓库路径和分支名称，还原本地所有改动，切换到指定分支并更新到最新版本
import os
import sys
import git
import subprocess

class GitTools():

    def reset_and_update(self, repo_path, branch_name):
        try:
            # subprocess.run(["git", "config", "--global", "core.quotepath", "false"], check=True)
            # subprocess.run(["git", "config", "--global", "gui.encoding", "utf-8"], check=True)
            # subprocess.run(["git", "config", "--global", "i18n.commit.encoding", "utf-8"], check=True)
            # subprocess.run(["git", "config", "--global", "i18n.logoutputencoding", "utf-8"], check=True)
            # 设置 Git 输出编码为 UTF-8
            os.environ['GIT_PYTHON_REFRESH'] = "quiet"
            os.environ['LANG'] = "en_US.UTF-8"

            # 切换到指定的git仓库目录
            os.chdir(repo_path)
            # 打开git仓库
            repo = git.Repo('.')
            # 重置本地所有改动
            repo.git.reset('--hard', 'HEAD')
            # 切换到指定分支
            repo.git.checkout(branch_name)
            # 拉取最新代码
            # repo.remotes.origin.pull()
            subprocess.run(['git', 'pull', '-v', '--', 'origin'], check=True, encoding='utf-8')

            print("成功还原本地改动并更新到最新版本")
        except subprocess.CalledProcessError as e:
            print(f"设置Git配置时发生错误: {e}")
        except Exception as e:
            print("发生错误:", e)
            sys.exit()

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--gitPath", required=True, help=u"git仓库路径")
    parser.add_argument("--gitBranch", required=True, help=u"git分支")
    args = parser.parse_args()

    tools = GitTools()
    tools.reset_and_update(args.gitPath, args.gitBranch)
